// KDRegister
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lz_app_core/constants/app_manager.dart';
import 'package:lz_base/kd_base.dart';
import 'package:lz_login/src/router/kd_login_router.dart';
import 'package:lz_login/src/serve/kd_login_api.dart';
import 'package:lz_login/src/widgets/kd_login_bottom_tel.dart';
import 'package:lz_app_core/extension/kd_extension.dart';
import 'package:lz_router/kd_router.dart';
import 'package:lz_ui/kd_ui.dart';
import 'package:get/get.dart';
import '../widgets/kd_pwd_warm_widget.dart';
import '../widgets/kd_user_protocal_widget.dart';
import '../widgets/kd_verification_code.dart';

class KDRegisterPage extends StatefulWidget {
  const KDRegisterPage({super.key});

  @override
  State<KDRegisterPage> createState() => _KDRegisterPageState();
}

class _KDRegisterPageState extends State<KDRegisterPage> {
  /// obs
  var _phoneErr = false.obs;
  var _pwdErr = false.obs;
  var _pwdWarmType = KDPwdWarmType.none.obs;
  var _msgCodeErr = false.obs;

  /// 用户输入
  var _phone = '';
  var _pwd = '';
  var _hasGetCode = false;
  var _code = '';
  bool checkProtocal = false;

  TextEditingController pwdTextController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return KDScaffold.scaffold(
      title: "注册",
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(KD.size(32)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const KDRedPointTitleWidget(title: "手机号"),
              _space(),
              Obx(
                () => KDFormInputWidget(
                  error: "请输入正确手机号",
                  isErr: _phoneErr.value,
                  child: Row(
                    children: [
                      Expanded(
                          child: KDTextFiled.aLineInput(
                              keyboardType: TextInputType.number,
                              maxLength: 11,
                              key: const ObjectKey('phone'),
                              onChanged: (e) {
                                _phone = e;
                                if (e.length == 11 && !e.isPhoneNumber) {
                                  _phoneErr.value = true;
                                } else {
                                  _phoneErr.value = false;
                                }
                              },
                              clearButtonMode: OverlayVisibilityMode.editing)),
                    ],
                  ),
                ),
              ),
              _codeInput,
              _space(),
              Obx(
                () => KDAccountPwdWidget(
                    title: "密码",
                    textController: pwdTextController,
                    isPwd: true,
                    error: _pwd.length < 6
                        ? "密码长度需6-20位"
                        : "请输入大于10位数密码或使用数字、字母、特殊字符号组合",
                    isErr: _pwdErr.value,
                    errorWidget: _pwdErr.value
                        ? null
                        : Obx(() => KDPwdWarmWidget(_pwdWarmType.value)),
                    onChange: KDInputDebounce((e) {
                      _pwd = e;

                      if (_pwd.length >= 6) {
                        _pwdErr.value = false;
                        _pwdWarmType.value = KDPwdWarmType.getType(_pwd);
                      } else {
                        _pwdErr.value = false;
                        _pwdWarmType.value = KDPwdWarmType.none;
                      }
                    }, 100)),
              ),
              _space(height: 104),
              KDBgWidget(
                bgColor: KDColor.main,
                margin: EdgeInsets.zero,
                height: KD.size(80),
                onTap: _next,
                child: Center(
                    child: Text(
                  "下一步",
                  style: TextStyle(color: Colors.white, fontSize: KD.font(32)),
                )),
              ),
              _space(),
              KDUserProtocalWidget(
                value: checkProtocal,
                checkCall: (e) => checkProtocal = e,
              ),
              const Flexible(
                  child: Align(
                alignment: Alignment.bottomCenter,
                child: KDTelWidget(),
              )),
            ],
          ),
        ),
      ),
    );
  }

  /// 按照dp
  Widget _space({double height = 16}) => SizedBox(
        height: KD.size(height),
      );

  /// 验证码
  Widget get _codeInput => KDVerificationCodeWidget(
        phoneCall: () => _phone,
        hasGetCode: (p0) => _hasGetCode = p0,
        inputCode: (p0) {
          _code = p0;
        },
      );

  _next() async {
    if (!_phone.isPhone) {
      _phoneErr.value = true;
    }

    if (_pwd.length < 6) {
      _pwdErr.value = true;
    }

    if (!_hasGetCode) {
      DialogUtils.showToast("请先获取验证码");
      return;
    }

    if (_hasGetCode && _code.isEmpty) {
      DialogUtils.showToast("请先输入验证码");
      return;
    }

    if (_hasGetCode && _code.length != 4) {
      DialogUtils.showToast("验证码有误");
      return;
    }

    if (_pwd.length < 6 || _pwdWarmType.value == KDPwdWarmType.weak) {
      // DialogUtils.showToast("密码设置太弱");
      _pwdErr.value = true;
      return;
    }

    if (!checkProtocal) {
      // KDAlert.alertCheck(context, subWidget: Text("12321321"));
      KDAlert.alertCheck(context,
          subWidget: KDUserProtocalWidget(
            showcheck: false,
            title: "点击同意表示您已经阅读并同意",
            font: KD.font(32),
            titleColor: KDColor.title,
            checkCall: (e) {},
          ),
          confirmTitle: "同意",
          confirm: _registerAndLogin);
      // DialogUtils.showToast("请先勾选用户协议");
      return;
    }
    _registerAndLogin();
  }

  /// 注册登陆
  _registerAndLogin() async {
    bool success =
        await KDLoginApi.register(phone: _phone, code: _code, pwd: _pwd);
    if (!success) return;

    /// 去登录
    bool isLogin = await KDLoginApi.login(phone: _phone, pwd: _pwd);
    if (isLogin) _alertOrder();
  }

  /// 去认证
  _alertOrder() {
    eventBus.fire(KDCertificationEvntBusModel(true));
  }
}
